Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [1]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [2]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[2]:
<matplotlib.image.AxesImage at 0x117ef17b8>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [3]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[3]:
<matplotlib.image.AxesImage at 0x11b0e3860>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x11b041978>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [5]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[5]:
<matplotlib.image.AxesImage at 0x11b1609e8>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [6]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!

    
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')


## find face area:
for (x,y,w,h) in faces:
    # find ROI for eyes
    roi_gray  = gray[y: y+h, x:x+w]
    roi_color = image_with_detections[y: y+h, x:x+w]
    
    ## look for eyes in ROI_GRAY
    eyes = eye_cascade.detectMultiScale(gray, 1.2, 6)
    
    ## loop over eyes to make boxes
    for (ex, ey, ew, eh) in eyes:
        cv2.rectangle(image_with_detections,
                     (ex, ey),
                     (ex + ew, ey + eh),
                     (0, 255, 0), 2)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Out[6]:
<matplotlib.image.AxesImage at 0x119c53c50>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [7]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        
        ## - Atul - 
        # 1. convert to gray
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # 2 - find faces
        faces   = face_cascade.detectMultiScale(gray_frame, 1.3, 5)
        
        ## 3 - find eyes in the faces, only then confirm
        for (x,y,w,h) in faces:
            ## 3a - make a red box for faces
            cv2.rectangle(frame,
                         (x, y),
                         (x+w, y+h),
                         (255,0,0), 3)
            
            ## 3b - find ROI for eyes
            roi_gray  = gray_frame[y: y+h, x: x+w]
            roi_color = frame[y: y+h, x: x+w]
            
            ## 3c - find eyes within the ROI
            eyes = eye_cascade.detectMultiScale(roi_gray, 1.2, 6)
            
            ## 3d - draw green box around eyes
            for (ex, ey, ew, eh) in eyes:
                cv2.rectangle(roi_color, 
                             (ex, ey),
                             (ex + ew, ey + eh),
                             (0, 255, 0), 2)
        
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
In [8]:
# Call the laptop camera face/eye detector function above
# laptop_camera_go()  ## IT WORKS !!

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [9]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[9]:
<matplotlib.image.AxesImage at 0x119bbba90>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [10]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 11
Out[10]:
<matplotlib.image.AxesImage at 0x11b139cc0>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [11]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!


denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise,
                                                None, 15, 15, 7, 21 )
In [12]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result

faces = face_cascade.detectMultiScale(denoised_image, 4, 6)
denoised_image_with_detections = np.copy(denoised_image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(denoised_image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Denoised Image with Face Detections')
ax1.imshow(denoised_image_with_detections)
Out[12]:
<matplotlib.image.AxesImage at 0x1254f2668>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [13]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[13]:
<matplotlib.image.AxesImage at 0x1156a4b38>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [14]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4
kernel = np.ones((4, 4), np.float32) / 16
gray_blur = cv2.filter2D(gray, -1, kernel)

## TODO: Then perform Canny edge detection and display the output

# Perform Canny edge detection
edges = cv2.Canny(gray_blur,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[14]:
<matplotlib.image.AxesImage at 0x11525f908>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [15]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[15]:
<matplotlib.image.AxesImage at 0x11f4237f0>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [16]:
## TODO: Implement face detection
def denoise(image):
    return cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 21, 7)

def blur_face(image):
    # 1 - denoise the image
    denoised_image = denoise(image)
    
    # 2 - gray it
    gray = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)
    
    # 3 - face detector
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    
    # 4 - detect faces
    faces = face_cascade.detectMultiScale(gray, 1.07, 15)
    
    # 5 - img copy
    imgcopy = np.copy(image)
    
    # 6 - blur faces found
    for (x, y, w, h) in faces:
        # blur faces
        ## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
        imgcopy[y: y+h, x: x+w] = cv2.blur(imgcopy[y: y+h, x: x+w], (100, 100))
        
    return imgcopy


# Load in the image
image = cv2.imread('images/gus.jpg')
# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

## do the blurring
blurred = blur_face(image)

## plot blurred image
# Display the image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Image with blurred faces')
ax2.imshow(blurred)
Out[16]:
<matplotlib.image.AxesImage at 0x128293f28>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [17]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        
        # blur the face
        blurred_frame = blur_face(frame)
        
        
        # Plot image from camera with detections marked
        cv2.imshow("face detection activated", blurred_frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [18]:
# Run laptop identity hider
#laptop_camera_go()

Blurring Face on Webcam Works

So this works 👍👍

Here's my picture with blurred face.


Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [19]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
Using TensorFlow backend.
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [20]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [21]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout, Conv2D
from keras.layers import Flatten, Dense, Activation
from keras import backend as K
import tensorflow as tf
In [23]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

K.clear_session()
session = tf.Session()
K.set_session(session)
# get TF graph
graph = K.get_session().graph

model = None
with graph.as_default():
    model = Sequential()
    
    model.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(Dropout(0.1))
    
    model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(Dropout(0.2))
    
    model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2,2)))
    model.add(Dropout(0.3))
    
    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(256, activation='relu'))
    model.add(Dropout(0.5))
    # final layer
    model.add(Dense(30))


# Summarize the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 16)        160       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 16)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 45, 45, 32)        4640      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 22, 22, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 22, 22, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 20, 20, 64)        18496     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 10, 10, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 10, 10, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 6400)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               3277312   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 256)               131328    
_________________________________________________________________
dropout_5 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                7710      
=================================================================
Total params: 3,439,646.0
Trainable params: 3,439,646.0
Non-trainable params: 0.0
_________________________________________________________________
In [30]:
## Show history

# graph the history of model.fit
def show_history_graph(history):
    
    plt.figure(figsize=(8,8))
    plt.subplot(221)
    # summarize history for accuracy
    plt.plot(history.history['acc'], label='train')
    plt.plot(history.history['val_acc'], label='test')
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(loc='upper left')
    
    # summarize history for loss
    plt.subplot(222)
    plt.plot(history.history['loss'], label='train')
    plt.plot(history.history['val_loss'], label='test')
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend( loc='upper left')
    
    plt.tight_layout()
    plt.show() 

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [32]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam

N_EPOCHS = 10
## TODO: Compile the model
#opt = keras.optimizers.Adam
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                shuffle=True)

## TODO: Save the model as model.h5
# model.save('my_model.h5')
Train on 1712 samples, validate on 428 samples
Epoch 1/10
1712/1712 [==============================] - 11s - loss: 0.0073 - acc: 0.6162 - mean_squared_error: 0.0073 - val_loss: 0.0047 - val_acc: 0.6963 - val_mean_squared_error: 0.0047
Epoch 2/10
1712/1712 [==============================] - 10s - loss: 0.0062 - acc: 0.6589 - mean_squared_error: 0.0062 - val_loss: 0.0043 - val_acc: 0.6963 - val_mean_squared_error: 0.0043
Epoch 3/10
1712/1712 [==============================] - 11s - loss: 0.0056 - acc: 0.6764 - mean_squared_error: 0.0056 - val_loss: 0.0040 - val_acc: 0.6963 - val_mean_squared_error: 0.0040
Epoch 4/10
1712/1712 [==============================] - 11s - loss: 0.0052 - acc: 0.6793 - mean_squared_error: 0.0052 - val_loss: 0.0038 - val_acc: 0.6963 - val_mean_squared_error: 0.0038
Epoch 5/10
1712/1712 [==============================] - 11s - loss: 0.0047 - acc: 0.6787 - mean_squared_error: 0.0047 - val_loss: 0.0034 - val_acc: 0.6963 - val_mean_squared_error: 0.0034
Epoch 6/10
1712/1712 [==============================] - 11s - loss: 0.0045 - acc: 0.6945 - mean_squared_error: 0.0045 - val_loss: 0.0034 - val_acc: 0.6963 - val_mean_squared_error: 0.0034
Epoch 7/10
1712/1712 [==============================] - 11s - loss: 0.0041 - acc: 0.6869 - mean_squared_error: 0.0041 - val_loss: 0.0031 - val_acc: 0.7009 - val_mean_squared_error: 0.0031
Epoch 8/10
1712/1712 [==============================] - 12s - loss: 0.0038 - acc: 0.6992 - mean_squared_error: 0.0038 - val_loss: 0.0027 - val_acc: 0.6963 - val_mean_squared_error: 0.0027 - ETA: 3s - loss: 0.0038 - acc: 0.6826 - mean_squared_error: 0.0038
Epoch 9/10
1712/1712 [==============================] - 12s - loss: 0.0037 - acc: 0.6974 - mean_squared_error: 0.0037 - val_loss: 0.0024 - val_acc: 0.7009 - val_mean_squared_error: 0.0024
Epoch 10/10
1712/1712 [==============================] - 12s - loss: 0.0034 - acc: 0.7004 - mean_squared_error: 0.0034 - val_loss: 0.0026 - val_acc: 0.6986 - val_mean_squared_error: 0.0026
In [33]:
# show history
show_history_graph(hist)
In [36]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def build_model2():
    K.clear_session()
    session = tf.Session()
    K.set_session(session)
    # get TF graph
    graph = K.get_session().graph

    model = None
    with graph.as_default():
        model = Sequential()
    
        model.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu'))
        # model.add(MaxPooling2D(pool_size=(2,2)))
    
        model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.4))
    
        model.add(Flatten())
        model.add(Dense(512, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(256, activation='relu'))
        model.add(Dropout(0.5))
        
        # final layer: 30 
        model.add(Dense(30))

    # Summarize the model
    model.summary()
    
    return model
In [37]:
model2 = build_model2()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 16)        160       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 16)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 45, 45, 32)        4640      
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 43, 43, 64)        18496     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 21, 21, 64)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 21, 21, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 28224)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               14451200  
_________________________________________________________________
dropout_3 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 256)               131328    
_________________________________________________________________
dropout_4 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                7710      
=================================================================
Total params: 14,613,534.0
Trainable params: 14,613,534.0
Non-trainable params: 0.0
_________________________________________________________________
In [40]:
from keras.callbacks import ModelCheckpoint   

checkpointer = ModelCheckpoint(filepath='model2.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 10
## TODO: Compile the model
#opt = keras.optimizers.Adam
model2.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model2.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
Train on 1712 samples, validate on 428 samples
Epoch 1/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0062 - acc: 0.6468 - mean_squared_error: 0.0062 Epoch 00000: val_loss improved from inf to 0.00415, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 29s - loss: 0.0062 - acc: 0.6460 - mean_squared_error: 0.0062 - val_loss: 0.0042 - val_acc: 0.6963 - val_mean_squared_error: 0.0042
Epoch 2/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0055 - acc: 0.6586 - mean_squared_error: 0.0055 Epoch 00001: val_loss improved from 0.00415 to 0.00341, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0054 - acc: 0.6600 - mean_squared_error: 0.0054 - val_loss: 0.0034 - val_acc: 0.6963 - val_mean_squared_error: 0.0034
Epoch 3/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0048 - acc: 0.6675 - mean_squared_error: 0.0048 Epoch 00002: val_loss improved from 0.00341 to 0.00303, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0048 - acc: 0.6665 - mean_squared_error: 0.0048 - val_loss: 0.0030 - val_acc: 0.6963 - val_mean_squared_error: 0.0030
Epoch 4/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0044 - acc: 0.6775 - mean_squared_error: 0.0044 Epoch 00003: val_loss improved from 0.00303 to 0.00290, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0044 - acc: 0.6787 - mean_squared_error: 0.0044 - val_loss: 0.0029 - val_acc: 0.6963 - val_mean_squared_error: 0.0029
Epoch 5/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0038 - acc: 0.6952 - mean_squared_error: 0.0038 Epoch 00004: val_loss improved from 0.00290 to 0.00245, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0038 - acc: 0.6957 - mean_squared_error: 0.0038 - val_loss: 0.0025 - val_acc: 0.7009 - val_mean_squared_error: 0.0025
Epoch 6/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0035 - acc: 0.6922 - mean_squared_error: 0.0035 Epoch 00005: val_loss improved from 0.00245 to 0.00219, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0035 - acc: 0.6928 - mean_squared_error: 0.0035 - val_loss: 0.0022 - val_acc: 0.7033 - val_mean_squared_error: 0.0022
Epoch 7/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7040 - mean_squared_error: 0.0033 Epoch 00006: val_loss did not improve
1712/1712 [==============================] - 28s - loss: 0.0033 - acc: 0.7039 - mean_squared_error: 0.0033 - val_loss: 0.0023 - val_acc: 0.7079 - val_mean_squared_error: 0.0023
Epoch 8/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.7040 - mean_squared_error: 0.0032 Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 28s - loss: 0.0032 - acc: 0.7044 - mean_squared_error: 0.0032 - val_loss: 0.0022 - val_acc: 0.6963 - val_mean_squared_error: 0.0022
Epoch 9/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0029 - acc: 0.7170 - mean_squared_error: 0.0029 Epoch 00008: val_loss improved from 0.00219 to 0.00212, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0029 - acc: 0.7173 - mean_squared_error: 0.0029 - val_loss: 0.0021 - val_acc: 0.7126 - val_mean_squared_error: 0.0021
Epoch 10/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0029 - acc: 0.7117 - mean_squared_error: 0.0029 Epoch 00009: val_loss improved from 0.00212 to 0.00198, saving model to model2.weights.best.hdf5
1712/1712 [==============================] - 30s - loss: 0.0029 - acc: 0.7120 - mean_squared_error: 0.0029 - val_loss: 0.0020 - val_acc: 0.7103 - val_mean_squared_error: 0.0020
In [41]:
show_history_graph(hist)
In [42]:
### Visualize some results

# MODEL switcher
model = model2     # CHANGE IF NECESSARY

y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)
In [43]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def build_model3():
    K.clear_session()
    session = tf.Session()
    K.set_session(session)
    # get TF graph
    graph = K.get_session().graph

    model = None
    with graph.as_default():
        model = Sequential()
    
        model.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=32, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=64, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.2))
    
        model.add(Flatten())
        model.add(Dense(256, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(128, activation='relu'))
        model.add(Dropout(0.5))
        
        # final layer: 30 
        model.add(Dense(30))

    # Summarize the model
    model.summary()
    
    return model
In [44]:
### MODEL 3
model3 = build_model3()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 16)        160       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 16)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 16)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 32)        2080      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 23, 23, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 22, 22, 64)        8256      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 11, 11, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 11, 11, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 7744)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 256)               1982720   
_________________________________________________________________
dropout_4 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 128)               32896     
_________________________________________________________________
dropout_5 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3870      
=================================================================
Total params: 2,029,982.0
Trainable params: 2,029,982.0
Non-trainable params: 0.0
_________________________________________________________________
In [46]:
### TRAINING ###

from keras.callbacks import ModelCheckpoint   

## Change Model Name
checkpointer = ModelCheckpoint(filepath='model3.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 10
## TODO: Compile the model
#opt = keras.optimizers.Adam
model3.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model3.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
Train on 1712 samples, validate on 428 samples
Epoch 1/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0574 - acc: 0.2358 - mean_squared_error: 0.0574 Epoch 00000: val_loss improved from inf to 0.02589, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0571 - acc: 0.2377 - mean_squared_error: 0.0571 - val_loss: 0.0259 - val_acc: 0.6963 - val_mean_squared_error: 0.0259
Epoch 2/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0190 - acc: 0.3644 - mean_squared_error: 0.0190 Epoch 00001: val_loss improved from 0.02589 to 0.01380, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0190 - acc: 0.3645 - mean_squared_error: 0.0190 - val_loss: 0.0138 - val_acc: 0.6963 - val_mean_squared_error: 0.0138
Epoch 3/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0128 - acc: 0.4564 - mean_squared_error: 0.0128 Epoch 00002: val_loss improved from 0.01380 to 0.00672, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0127 - acc: 0.4550 - mean_squared_error: 0.0127 - val_loss: 0.0067 - val_acc: 0.6963 - val_mean_squared_error: 0.0067
Epoch 4/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0101 - acc: 0.5224 - mean_squared_error: 0.0101 Epoch 00003: val_loss improved from 0.00672 to 0.00442, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0102 - acc: 0.5245 - mean_squared_error: 0.0102 - val_loss: 0.0044 - val_acc: 0.6963 - val_mean_squared_error: 0.0044
Epoch 5/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0087 - acc: 0.5613 - mean_squared_error: 0.0087 Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 14s - loss: 0.0087 - acc: 0.5602 - mean_squared_error: 0.0087 - val_loss: 0.0044 - val_acc: 0.6963 - val_mean_squared_error: 0.0044
Epoch 6/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0080 - acc: 0.5991 - mean_squared_error: 0.0080 Epoch 00005: val_loss improved from 0.00442 to 0.00437, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0079 - acc: 0.5975 - mean_squared_error: 0.0079 - val_loss: 0.0044 - val_acc: 0.6963 - val_mean_squared_error: 0.0044
Epoch 7/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0074 - acc: 0.6085 - mean_squared_error: 0.0074 Epoch 00006: val_loss improved from 0.00437 to 0.00409, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0074 - acc: 0.6092 - mean_squared_error: 0.0074 - val_loss: 0.0041 - val_acc: 0.6963 - val_mean_squared_error: 0.0041
Epoch 8/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0072 - acc: 0.6008 - mean_squared_error: 0.0072 Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 14s - loss: 0.0072 - acc: 0.5999 - mean_squared_error: 0.0072 - val_loss: 0.0042 - val_acc: 0.6963 - val_mean_squared_error: 0.0042
Epoch 9/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0067 - acc: 0.6315 - mean_squared_error: 0.0067 Epoch 00008: val_loss improved from 0.00409 to 0.00400, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 14s - loss: 0.0067 - acc: 0.6320 - mean_squared_error: 0.0067 - val_loss: 0.0040 - val_acc: 0.6963 - val_mean_squared_error: 0.0040
Epoch 10/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0064 - acc: 0.6462 - mean_squared_error: 0.0064 Epoch 00009: val_loss improved from 0.00400 to 0.00394, saving model to model3.weights.best.hdf5
1712/1712 [==============================] - 15s - loss: 0.0064 - acc: 0.6472 - mean_squared_error: 0.0064 - val_loss: 0.0039 - val_acc: 0.6963 - val_mean_squared_error: 0.0039
In [47]:
show_history_graph(hist)
In [48]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def build_model4():
    K.clear_session()
    session = tf.Session()
    K.set_session(session)
    # get TF graph
    graph = K.get_session().graph

    model = None
    with graph.as_default():
        model = Sequential()
    
        model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=32, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.2))
    
        model.add(Conv2D(filters=64, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.3))
    
        model.add(Flatten())
        model.add(Dense(500, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(200, activation='relu'))
        model.add(Dropout(0.5))
        
        # final layer: 30 
        model.add(Dense(30))

    # Summarize the model
    model.summary()
    
    return model
In [49]:
## MODEL 4
model4 = build_model4()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 32)        320       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 32)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 32)        4128      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 23, 23, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 22, 22, 64)        8256      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 11, 11, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 11, 11, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 7744)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 500)               3872500   
_________________________________________________________________
dropout_4 (Dropout)          (None, 500)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 200)               100200    
_________________________________________________________________
dropout_5 (Dropout)          (None, 200)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                6030      
=================================================================
Total params: 3,991,434.0
Trainable params: 3,991,434.0
Non-trainable params: 0.0
_________________________________________________________________
In [50]:
### TRAINING ###

from keras.callbacks import ModelCheckpoint   

## Change Model Name
checkpointer = ModelCheckpoint(filepath='model4.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 10
## TODO: Compile the model
#opt = keras.optimizers.Adam
model4.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model4.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
show_history_graph(hist)
Train on 1712 samples, validate on 428 samples
Epoch 1/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0381 - acc: 0.3880 - mean_squared_error: 0.0381 Epoch 00000: val_loss improved from inf to 0.02301, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0378 - acc: 0.3884 - mean_squared_error: 0.0378 - val_loss: 0.0230 - val_acc: 0.6963 - val_mean_squared_error: 0.0230
Epoch 2/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0134 - acc: 0.5236 - mean_squared_error: 0.0134 Epoch 00001: val_loss improved from 0.02301 to 0.00879, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0134 - acc: 0.5245 - mean_squared_error: 0.0134 - val_loss: 0.0088 - val_acc: 0.6963 - val_mean_squared_error: 0.0088
Epoch 3/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0100 - acc: 0.5531 - mean_squared_error: 0.0100 Epoch 00002: val_loss improved from 0.00879 to 0.00751, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0100 - acc: 0.5520 - mean_squared_error: 0.0100 - val_loss: 0.0075 - val_acc: 0.6963 - val_mean_squared_error: 0.0075
Epoch 4/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0083 - acc: 0.5991 - mean_squared_error: 0.0083 Epoch 00003: val_loss improved from 0.00751 to 0.00471, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0083 - acc: 0.6005 - mean_squared_error: 0.0083 - val_loss: 0.0047 - val_acc: 0.6963 - val_mean_squared_error: 0.0047
Epoch 5/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0076 - acc: 0.6061 - mean_squared_error: 0.0076 Epoch 00004: val_loss improved from 0.00471 to 0.00403, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0076 - acc: 0.6057 - mean_squared_error: 0.0076 - val_loss: 0.0040 - val_acc: 0.6963 - val_mean_squared_error: 0.0040
Epoch 6/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0068 - acc: 0.6315 - mean_squared_error: 0.0068 Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0068 - acc: 0.6326 - mean_squared_error: 0.0068 - val_loss: 0.0041 - val_acc: 0.6963 - val_mean_squared_error: 0.0041
Epoch 7/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0063 - acc: 0.6380 - mean_squared_error: 0.0063 Epoch 00006: val_loss improved from 0.00403 to 0.00391, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0064 - acc: 0.6379 - mean_squared_error: 0.0064 - val_loss: 0.0039 - val_acc: 0.6963 - val_mean_squared_error: 0.0039
Epoch 8/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0060 - acc: 0.6498 - mean_squared_error: 0.0060 Epoch 00007: val_loss improved from 0.00391 to 0.00385, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0060 - acc: 0.6489 - mean_squared_error: 0.0060 - val_loss: 0.0039 - val_acc: 0.6963 - val_mean_squared_error: 0.0039
Epoch 9/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0057 - acc: 0.6568 - mean_squared_error: 0.0057 Epoch 00008: val_loss improved from 0.00385 to 0.00359, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0057 - acc: 0.6571 - mean_squared_error: 0.0057 - val_loss: 0.0036 - val_acc: 0.6963 - val_mean_squared_error: 0.0036
Epoch 10/10
1696/1712 [============================>.] - ETA: 0s - loss: 0.0053 - acc: 0.6645 - mean_squared_error: 0.0053 Epoch 00009: val_loss improved from 0.00359 to 0.00328, saving model to model4.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0053 - acc: 0.6647 - mean_squared_error: 0.0053 - val_loss: 0.0033 - val_acc: 0.6963 - val_mean_squared_error: 0.0033
In [51]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def build_model5():
    K.clear_session()
    session = tf.Session()
    K.set_session(session)
    # get TF graph
    graph = K.get_session().graph

    model = None
    with graph.as_default():
        model = Sequential()
    
        model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=64, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.2))
    
        model.add(Conv2D(filters=128, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.3))
    
        model.add(Flatten())
        model.add(Dense(512, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(256, activation='relu'))
        model.add(Dropout(0.5))
        
        # final layer: 30 
        model.add(Dense(30))

    # Summarize the model
    model.summary()
    
    return model
In [52]:
### MODEL 5 ###
model5 = build_model5()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 32)        320       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 32)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 64)        8256      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 64)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 23, 23, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 22, 22, 128)       32896     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 11, 11, 128)       0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 11, 11, 128)       0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 15488)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               7930368   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 256)               131328    
_________________________________________________________________
dropout_5 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                7710      
=================================================================
Total params: 8,110,878.0
Trainable params: 8,110,878.0
Non-trainable params: 0.0
_________________________________________________________________
In [53]:
### TRAINING ###

from keras.callbacks import ModelCheckpoint   

## Change Model Name
checkpointer = ModelCheckpoint(filepath='model5.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 20
## TODO: Compile the model
#opt = keras.optimizers.Adam
model5.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model5.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
show_history_graph(hist)
Train on 1712 samples, validate on 428 samples
Epoch 1/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0481 - acc: 0.3691 - mean_squared_error: 0.0481      Epoch 00000: val_loss improved from inf to 0.03445, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 35s - loss: 0.0478 - acc: 0.3703 - mean_squared_error: 0.0478 - val_loss: 0.0345 - val_acc: 0.6963 - val_mean_squared_error: 0.0345
Epoch 2/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0134 - acc: 0.5035 - mean_squared_error: 0.0134 Epoch 00001: val_loss improved from 0.03445 to 0.01411, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 33s - loss: 0.0134 - acc: 0.5041 - mean_squared_error: 0.0134 - val_loss: 0.0141 - val_acc: 0.6963 - val_mean_squared_error: 0.0141
Epoch 3/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0099 - acc: 0.5466 - mean_squared_error: 0.0099 Epoch 00002: val_loss improved from 0.01411 to 0.00852, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 33s - loss: 0.0099 - acc: 0.5485 - mean_squared_error: 0.0099 - val_loss: 0.0085 - val_acc: 0.6963 - val_mean_squared_error: 0.0085
Epoch 4/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0082 - acc: 0.5961 - mean_squared_error: 0.0082 Epoch 00003: val_loss improved from 0.00852 to 0.00468, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 33s - loss: 0.0082 - acc: 0.5952 - mean_squared_error: 0.0082 - val_loss: 0.0047 - val_acc: 0.6963 - val_mean_squared_error: 0.0047
Epoch 5/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0074 - acc: 0.6185 - mean_squared_error: 0.0074 Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 33s - loss: 0.0074 - acc: 0.6180 - mean_squared_error: 0.0074 - val_loss: 0.0051 - val_acc: 0.6963 - val_mean_squared_error: 0.0051
Epoch 6/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0068 - acc: 0.6073 - mean_squared_error: 0.0068 Epoch 00005: val_loss improved from 0.00468 to 0.00421, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 33s - loss: 0.0068 - acc: 0.6069 - mean_squared_error: 0.0068 - val_loss: 0.0042 - val_acc: 0.6963 - val_mean_squared_error: 0.0042
Epoch 7/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0064 - acc: 0.6445 - mean_squared_error: 0.0064 Epoch 00006: val_loss did not improve
1712/1712 [==============================] - 34s - loss: 0.0063 - acc: 0.6425 - mean_squared_error: 0.0063 - val_loss: 0.0043 - val_acc: 0.6963 - val_mean_squared_error: 0.0043
Epoch 8/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0059 - acc: 0.6545 - mean_squared_error: 0.0059 Epoch 00007: val_loss improved from 0.00421 to 0.00374, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 34s - loss: 0.0060 - acc: 0.6536 - mean_squared_error: 0.0060 - val_loss: 0.0037 - val_acc: 0.6963 - val_mean_squared_error: 0.0037
Epoch 9/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0058 - acc: 0.6680 - mean_squared_error: 0.0058 Epoch 00008: val_loss improved from 0.00374 to 0.00357, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 34s - loss: 0.0058 - acc: 0.6676 - mean_squared_error: 0.0058 - val_loss: 0.0036 - val_acc: 0.6963 - val_mean_squared_error: 0.0036
Epoch 10/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0054 - acc: 0.6757 - mean_squared_error: 0.0054 Epoch 00009: val_loss improved from 0.00357 to 0.00337, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 34s - loss: 0.0054 - acc: 0.6764 - mean_squared_error: 0.0054 - val_loss: 0.0034 - val_acc: 0.6963 - val_mean_squared_error: 0.0034
Epoch 11/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0051 - acc: 0.6704 - mean_squared_error: 0.0051 Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 34s - loss: 0.0051 - acc: 0.6700 - mean_squared_error: 0.0051 - val_loss: 0.0036 - val_acc: 0.6963 - val_mean_squared_error: 0.0036
Epoch 12/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0049 - acc: 0.6834 - mean_squared_error: 0.0049 Epoch 00011: val_loss improved from 0.00337 to 0.00305, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 34s - loss: 0.0049 - acc: 0.6852 - mean_squared_error: 0.0049 - val_loss: 0.0030 - val_acc: 0.6963 - val_mean_squared_error: 0.0030
Epoch 13/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.6863 - mean_squared_error: 0.0047 Epoch 00012: val_loss improved from 0.00305 to 0.00301, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 34s - loss: 0.0047 - acc: 0.6857 - mean_squared_error: 0.0047 - val_loss: 0.0030 - val_acc: 0.6963 - val_mean_squared_error: 0.0030
Epoch 14/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0045 - acc: 0.6787 - mean_squared_error: 0.0045 Epoch 00013: val_loss did not improve
1712/1712 [==============================] - 34s - loss: 0.0045 - acc: 0.6770 - mean_squared_error: 0.0045 - val_loss: 0.0031 - val_acc: 0.6986 - val_mean_squared_error: 0.0031
Epoch 15/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0043 - acc: 0.6680 - mean_squared_error: 0.0043 Epoch 00014: val_loss improved from 0.00301 to 0.00266, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 26s - loss: 0.0043 - acc: 0.6676 - mean_squared_error: 0.0043 - val_loss: 0.0027 - val_acc: 0.6986 - val_mean_squared_error: 0.0027
Epoch 16/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0042 - acc: 0.7011 - mean_squared_error: 0.0042 Epoch 00015: val_loss improved from 0.00266 to 0.00258, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 29s - loss: 0.0043 - acc: 0.6980 - mean_squared_error: 0.0043 - val_loss: 0.0026 - val_acc: 0.7009 - val_mean_squared_error: 0.0026
Epoch 17/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0040 - acc: 0.6958 - mean_squared_error: 0.0040 Epoch 00016: val_loss did not improve
1712/1712 [==============================] - 33s - loss: 0.0040 - acc: 0.6963 - mean_squared_error: 0.0040 - val_loss: 0.0027 - val_acc: 0.7009 - val_mean_squared_error: 0.0027
Epoch 18/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0040 - acc: 0.7017 - mean_squared_error: 0.0040 Epoch 00017: val_loss did not improve
1712/1712 [==============================] - 27s - loss: 0.0040 - acc: 0.7009 - mean_squared_error: 0.0040 - val_loss: 0.0026 - val_acc: 0.7009 - val_mean_squared_error: 0.0026
Epoch 19/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0038 - acc: 0.6963 - mean_squared_error: 0.0038 Epoch 00018: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0038 - acc: 0.6968 - mean_squared_error: 0.0038 - val_loss: 0.0028 - val_acc: 0.6986 - val_mean_squared_error: 0.0028
Epoch 20/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0037 - acc: 0.7017 - mean_squared_error: 0.0037 Epoch 00019: val_loss improved from 0.00258 to 0.00240, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0037 - acc: 0.7009 - mean_squared_error: 0.0037 - val_loss: 0.0024 - val_acc: 0.7079 - val_mean_squared_error: 0.0024
In [54]:
## Change Model Name
checkpointer = ModelCheckpoint(filepath='model5.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 25
## TODO: Compile the model
#opt = keras.optimizers.Adam
# model5.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model5.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
show_history_graph(hist)
Train on 1712 samples, validate on 428 samples
Epoch 1/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0037 - acc: 0.7040 - mean_squared_error: 0.0037 Epoch 00000: val_loss improved from inf to 0.00242, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0037 - acc: 0.7033 - mean_squared_error: 0.0037 - val_loss: 0.0024 - val_acc: 0.7150 - val_mean_squared_error: 0.0024
Epoch 2/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0034 - acc: 0.7075 - mean_squared_error: 0.0034 Epoch 00001: val_loss improved from 0.00242 to 0.00238, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0034 - acc: 0.7079 - mean_squared_error: 0.0034 - val_loss: 0.0024 - val_acc: 0.7126 - val_mean_squared_error: 0.0024
Epoch 3/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0035 - acc: 0.6946 - mean_squared_error: 0.0035 Epoch 00002: val_loss improved from 0.00238 to 0.00233, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0035 - acc: 0.6963 - mean_squared_error: 0.0035 - val_loss: 0.0023 - val_acc: 0.7103 - val_mean_squared_error: 0.0023
Epoch 4/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7075 - mean_squared_error: 0.0033 Epoch 00003: val_loss improved from 0.00233 to 0.00228, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0033 - acc: 0.7074 - mean_squared_error: 0.0033 - val_loss: 0.0023 - val_acc: 0.7079 - val_mean_squared_error: 0.0023
Epoch 5/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7129 - mean_squared_error: 0.0033 Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0033 - acc: 0.7120 - mean_squared_error: 0.0033 - val_loss: 0.0023 - val_acc: 0.7126 - val_mean_squared_error: 0.0023
Epoch 6/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.7158 - mean_squared_error: 0.0032 Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0032 - acc: 0.7161 - mean_squared_error: 0.0032 - val_loss: 0.0023 - val_acc: 0.7079 - val_mean_squared_error: 0.0023
Epoch 7/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0031 - acc: 0.7188 - mean_squared_error: 0.0031 Epoch 00006: val_loss improved from 0.00228 to 0.00201, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0031 - acc: 0.7185 - mean_squared_error: 0.0031 - val_loss: 0.0020 - val_acc: 0.7103 - val_mean_squared_error: 0.0020
Epoch 8/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0031 - acc: 0.7058 - mean_squared_error: 0.0031 Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 25s - loss: 0.0031 - acc: 0.7056 - mean_squared_error: 0.0031 - val_loss: 0.0021 - val_acc: 0.7103 - val_mean_squared_error: 0.0021
Epoch 9/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0030 - acc: 0.7070 - mean_squared_error: 0.0030 Epoch 00008: val_loss did not improve
1712/1712 [==============================] - 25s - loss: 0.0030 - acc: 0.7085 - mean_squared_error: 0.0030 - val_loss: 0.0020 - val_acc: 0.7103 - val_mean_squared_error: 0.0020
Epoch 10/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0029 - acc: 0.7146 - mean_squared_error: 0.0029 Epoch 00009: val_loss improved from 0.00201 to 0.00196, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 25s - loss: 0.0029 - acc: 0.7150 - mean_squared_error: 0.0029 - val_loss: 0.0020 - val_acc: 0.7126 - val_mean_squared_error: 0.0020
Epoch 11/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0029 - acc: 0.7199 - mean_squared_error: 0.0029 Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0029 - acc: 0.7202 - mean_squared_error: 0.0029 - val_loss: 0.0020 - val_acc: 0.7196 - val_mean_squared_error: 0.0020
Epoch 12/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0028 - acc: 0.7193 - mean_squared_error: 0.0028 Epoch 00011: val_loss improved from 0.00196 to 0.00186, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0028 - acc: 0.7190 - mean_squared_error: 0.0028 - val_loss: 0.0019 - val_acc: 0.7056 - val_mean_squared_error: 0.0019
Epoch 13/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0028 - acc: 0.7099 - mean_squared_error: 0.0028 Epoch 00012: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0028 - acc: 0.7091 - mean_squared_error: 0.0028 - val_loss: 0.0019 - val_acc: 0.7266 - val_mean_squared_error: 0.0019
Epoch 14/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0027 - acc: 0.7241 - mean_squared_error: 0.0027 Epoch 00013: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0027 - acc: 0.7237 - mean_squared_error: 0.0027 - val_loss: 0.0019 - val_acc: 0.7220 - val_mean_squared_error: 0.0019
Epoch 15/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0027 - acc: 0.7164 - mean_squared_error: 0.0027 Epoch 00014: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0027 - acc: 0.7167 - mean_squared_error: 0.0027 - val_loss: 0.0021 - val_acc: 0.7266 - val_mean_squared_error: 0.0021
Epoch 16/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0026 - acc: 0.7223 - mean_squared_error: 0.0026 Epoch 00015: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0026 - acc: 0.7220 - mean_squared_error: 0.0026 - val_loss: 0.0019 - val_acc: 0.7313 - val_mean_squared_error: 0.0019
Epoch 17/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0026 - acc: 0.7152 - mean_squared_error: 0.0026 Epoch 00016: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0026 - acc: 0.7161 - mean_squared_error: 0.0026 - val_loss: 0.0019 - val_acc: 0.7266 - val_mean_squared_error: 0.0019
Epoch 18/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0025 - acc: 0.7353 - mean_squared_error: 0.0025 Epoch 00017: val_loss improved from 0.00186 to 0.00183, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0025 - acc: 0.7371 - mean_squared_error: 0.0025 - val_loss: 0.0018 - val_acc: 0.7173 - val_mean_squared_error: 0.0018
Epoch 19/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0025 - acc: 0.7217 - mean_squared_error: 0.0025 Epoch 00018: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0025 - acc: 0.7202 - mean_squared_error: 0.0025 - val_loss: 0.0019 - val_acc: 0.7243 - val_mean_squared_error: 0.0019
Epoch 20/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7264 - mean_squared_error: 0.0023 Epoch 00019: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0023 - acc: 0.7278 - mean_squared_error: 0.0023 - val_loss: 0.0020 - val_acc: 0.7220 - val_mean_squared_error: 0.0020
Epoch 21/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0024 - acc: 0.7241 - mean_squared_error: 0.0024 Epoch 00020: val_loss improved from 0.00183 to 0.00175, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0024 - acc: 0.7231 - mean_squared_error: 0.0024 - val_loss: 0.0018 - val_acc: 0.7220 - val_mean_squared_error: 0.0018
Epoch 22/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0024 - acc: 0.7182 - mean_squared_error: 0.0024 Epoch 00021: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0024 - acc: 0.7173 - mean_squared_error: 0.0024 - val_loss: 0.0019 - val_acc: 0.7103 - val_mean_squared_error: 0.0019
Epoch 23/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7235 - mean_squared_error: 0.0023 Epoch 00022: val_loss improved from 0.00175 to 0.00174, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0023 - acc: 0.7249 - mean_squared_error: 0.0023 - val_loss: 0.0017 - val_acc: 0.7196 - val_mean_squared_error: 0.0017
Epoch 24/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7211 - mean_squared_error: 0.0023 Epoch 00023: val_loss improved from 0.00174 to 0.00173, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 28s - loss: 0.0022 - acc: 0.7208 - mean_squared_error: 0.0022 - val_loss: 0.0017 - val_acc: 0.7360 - val_mean_squared_error: 0.0017
Epoch 25/25
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7241 - mean_squared_error: 0.0023 Epoch 00024: val_loss improved from 0.00173 to 0.00172, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0023 - acc: 0.7237 - mean_squared_error: 0.0023 - val_loss: 0.0017 - val_acc: 0.7173 - val_mean_squared_error: 0.0017
In [55]:
## Change Model Name
checkpointer = ModelCheckpoint(filepath='model5.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
N_EPOCHS = 20
## TODO: Compile the model
#opt = keras.optimizers.Adam
# model5.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mse'] )

## TODO: Train the model
hist = model5.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
show_history_graph(hist)
Train on 1712 samples, validate on 428 samples
Epoch 1/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0022 - acc: 0.7241 - mean_squared_error: 0.0022 Epoch 00000: val_loss improved from inf to 0.00159, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0022 - acc: 0.7237 - mean_squared_error: 0.0022 - val_loss: 0.0016 - val_acc: 0.7220 - val_mean_squared_error: 0.0016
Epoch 2/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0022 - acc: 0.7382 - mean_squared_error: 0.0022 Epoch 00001: val_loss did not improve
1712/1712 [==============================] - 21s - loss: 0.0022 - acc: 0.7389 - mean_squared_error: 0.0022 - val_loss: 0.0016 - val_acc: 0.7290 - val_mean_squared_error: 0.0016
Epoch 3/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7294 - mean_squared_error: 0.0021 Epoch 00002: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0021 - acc: 0.7278 - mean_squared_error: 0.0021 - val_loss: 0.0017 - val_acc: 0.7243 - val_mean_squared_error: 0.0017
Epoch 4/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7417 - mean_squared_error: 0.0021 Epoch 00003: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0021 - acc: 0.7401 - mean_squared_error: 0.0021 - val_loss: 0.0017 - val_acc: 0.7126 - val_mean_squared_error: 0.0017
Epoch 5/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7311 - mean_squared_error: 0.0021 Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0021 - acc: 0.7313 - mean_squared_error: 0.0021 - val_loss: 0.0016 - val_acc: 0.7173 - val_mean_squared_error: 0.0016
Epoch 6/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7146 - mean_squared_error: 0.0021 Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0021 - acc: 0.7132 - mean_squared_error: 0.0021 - val_loss: 0.0016 - val_acc: 0.7243 - val_mean_squared_error: 0.0016
Epoch 7/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7235 - mean_squared_error: 0.0021 Epoch 00006: val_loss did not improve
1712/1712 [==============================] - 22s - loss: 0.0021 - acc: 0.7243 - mean_squared_error: 0.0021 - val_loss: 0.0016 - val_acc: 0.7220 - val_mean_squared_error: 0.0016
Epoch 8/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7158 - mean_squared_error: 0.0020 Epoch 00007: val_loss improved from 0.00159 to 0.00152, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 22s - loss: 0.0020 - acc: 0.7167 - mean_squared_error: 0.0020 - val_loss: 0.0015 - val_acc: 0.7266 - val_mean_squared_error: 0.0015
Epoch 9/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7229 - mean_squared_error: 0.0020 Epoch 00008: val_loss improved from 0.00152 to 0.00151, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0020 - acc: 0.7225 - mean_squared_error: 0.0020 - val_loss: 0.0015 - val_acc: 0.7336 - val_mean_squared_error: 0.0015
Epoch 10/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7270 - mean_squared_error: 0.0020 Epoch 00009: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0020 - acc: 0.7266 - mean_squared_error: 0.0020 - val_loss: 0.0016 - val_acc: 0.7313 - val_mean_squared_error: 0.0016
Epoch 11/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7217 - mean_squared_error: 0.0020 Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0020 - acc: 0.7220 - mean_squared_error: 0.0020 - val_loss: 0.0016 - val_acc: 0.7290 - val_mean_squared_error: 0.0016
Epoch 12/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7370 - mean_squared_error: 0.0019 Epoch 00011: val_loss improved from 0.00151 to 0.00150, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 23s - loss: 0.0019 - acc: 0.7371 - mean_squared_error: 0.0019 - val_loss: 0.0015 - val_acc: 0.7103 - val_mean_squared_error: 0.0015
Epoch 13/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7235 - mean_squared_error: 0.0019 Epoch 00012: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0019 - acc: 0.7243 - mean_squared_error: 0.0019 - val_loss: 0.0016 - val_acc: 0.7126 - val_mean_squared_error: 0.0016
Epoch 14/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7406 - mean_squared_error: 0.0019 Epoch 00013: val_loss improved from 0.00150 to 0.00149, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0019 - acc: 0.7407 - mean_squared_error: 0.0019 - val_loss: 0.0015 - val_acc: 0.7173 - val_mean_squared_error: 0.0015
Epoch 15/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7323 - mean_squared_error: 0.0019 Epoch 00014: val_loss improved from 0.00149 to 0.00145, saving model to model5.weights.best.hdf5
1712/1712 [==============================] - 24s - loss: 0.0019 - acc: 0.7325 - mean_squared_error: 0.0019 - val_loss: 0.0015 - val_acc: 0.7150 - val_mean_squared_error: 0.0015
Epoch 16/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7229 - mean_squared_error: 0.0019 Epoch 00015: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0019 - acc: 0.7237 - mean_squared_error: 0.0019 - val_loss: 0.0015 - val_acc: 0.7243 - val_mean_squared_error: 0.0015
Epoch 17/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7364 - mean_squared_error: 0.0018 Epoch 00016: val_loss did not improve
1712/1712 [==============================] - 27s - loss: 0.0018 - acc: 0.7342 - mean_squared_error: 0.0018 - val_loss: 0.0015 - val_acc: 0.7383 - val_mean_squared_error: 0.0015
Epoch 18/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7488 - mean_squared_error: 0.0019 Epoch 00017: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0019 - acc: 0.7488 - mean_squared_error: 0.0019 - val_loss: 0.0016 - val_acc: 0.7313 - val_mean_squared_error: 0.0016
Epoch 19/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7370 - mean_squared_error: 0.0018 Epoch 00018: val_loss did not improve
1712/1712 [==============================] - 23s - loss: 0.0018 - acc: 0.7395 - mean_squared_error: 0.0018 - val_loss: 0.0016 - val_acc: 0.7103 - val_mean_squared_error: 0.0016
Epoch 20/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7335 - mean_squared_error: 0.0018 Epoch 00019: val_loss did not improve
1712/1712 [==============================] - 24s - loss: 0.0018 - acc: 0.7331 - mean_squared_error: 0.0018 - val_loss: 0.0015 - val_acc: 0.7290 - val_mean_squared_error: 0.0015
In [56]:
### Visualize some results

# MODEL switcher
model = model5     # CHANGE IF NECESSARY

y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)
In [65]:
## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

def build_model6():
    K.clear_session()
    session = tf.Session()
    K.set_session(session)
    # get TF graph
    graph = K.get_session().graph

    model = None
    with graph.as_default():
        model = Sequential()
    
        model.add(Conv2D(filters=8, kernel_size=(3,3), activation='relu', input_shape=(96,96,1)) )
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.1))
    
        model.add(Conv2D(filters=16, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.2))
    
        model.add(Conv2D(filters=32, kernel_size=(2,2), activation='relu'))
        model.add(MaxPooling2D(pool_size=(2,2)))
        model.add(Dropout(0.2))
    
        model.add(Flatten())
        model.add(Dense(256, activation='relu'))
        model.add(Dropout(0.5))
        model.add(Dense(128, activation='relu'))
        model.add(Dropout(0.3))
        
        # final layer: 30 
        model.add(Dense(30))

    # Summarize the model
    model.summary()
    
    return model
In [66]:
### model 6
model6 = build_model6()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 8)         80        
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 8)         0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 8)         0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 16)        528       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 16)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 23, 23, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 22, 22, 32)        2080      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 11, 11, 32)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 11, 11, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 3872)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 256)               991488    
_________________________________________________________________
dropout_4 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 128)               32896     
_________________________________________________________________
dropout_5 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3870      
=================================================================
Total params: 1,030,942.0
Trainable params: 1,030,942.0
Non-trainable params: 0.0
_________________________________________________________________

Testing Different Optimizers

So the model above is small enough. Let's test a few optimizers and see how they perform.

In [67]:
from keras.callbacks import ModelCheckpoint   


N_EPOCHS = 12
## TODO: Compile the model
#opt = keras.optimizers.Adam

optimizers = ['SGD', 'RMSprop', 'Adam', 'Nadam', 'Nesterov']
for opt in optimizers:
    if opt == 'Nesterov':
        opt = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    else:
        opt = opt

    ## compile model
    model6.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy', 'mse'] )
    
    filepath = 'model6-' + opt + '.weights.best.hdf5'
    print('--- using optimizer: {} --- saving weights in: {} ---\n'.format(opt, filepath))
    
    checkpointer = ModelCheckpoint(filepath=filepath, verbose=1, 
                               save_best_only=True)

    ## TODO: Train the model
    hist = model6.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer],
                shuffle=True)
    ## plot graph
    show_history_graph(hist)
--- using optimizer: SGD --- saving weights in: model6-SGD.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.1515 - acc: 0.0908 - mean_squared_error: 0.1515 Epoch 00000: val_loss improved from inf to 0.11663, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.1512 - acc: 0.0905 - mean_squared_error: 0.1512 - val_loss: 0.1166 - val_acc: 0.1729 - val_mean_squared_error: 0.1166
Epoch 2/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.1063 - acc: 0.1244 - mean_squared_error: 0.1063    Epoch 00001: val_loss improved from 0.11663 to 0.08905, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 4s - loss: 0.1063 - acc: 0.1250 - mean_squared_error: 0.1063 - val_loss: 0.0890 - val_acc: 0.2453 - val_mean_squared_error: 0.0890
Epoch 3/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0841 - acc: 0.1551 - mean_squared_error: 0.0841Epoch 00002: val_loss improved from 0.08905 to 0.06888, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0840 - acc: 0.1536 - mean_squared_error: 0.0840 - val_loss: 0.0689 - val_acc: 0.2523 - val_mean_squared_error: 0.0689
Epoch 4/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0694 - acc: 0.1810 - mean_squared_error: 0.0694Epoch 00003: val_loss improved from 0.06888 to 0.05686, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0694 - acc: 0.1817 - mean_squared_error: 0.0694 - val_loss: 0.0569 - val_acc: 0.2523 - val_mean_squared_error: 0.0569
Epoch 5/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0588 - acc: 0.1969 - mean_squared_error: 0.0588Epoch 00004: val_loss improved from 0.05686 to 0.04797, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0588 - acc: 0.1980 - mean_squared_error: 0.0588 - val_loss: 0.0480 - val_acc: 0.2523 - val_mean_squared_error: 0.0480
Epoch 6/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0513 - acc: 0.2087 - mean_squared_error: 0.0513Epoch 00005: val_loss improved from 0.04797 to 0.04280, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0512 - acc: 0.2091 - mean_squared_error: 0.0512 - val_loss: 0.0428 - val_acc: 0.2523 - val_mean_squared_error: 0.0428
Epoch 7/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0456 - acc: 0.2476 - mean_squared_error: 0.0456Epoch 00006: val_loss improved from 0.04280 to 0.03777, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0457 - acc: 0.2465 - mean_squared_error: 0.0457 - val_loss: 0.0378 - val_acc: 0.2523 - val_mean_squared_error: 0.0378
Epoch 8/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0410 - acc: 0.2677 - mean_squared_error: 0.0410Epoch 00007: val_loss improved from 0.03777 to 0.03472, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0410 - acc: 0.2687 - mean_squared_error: 0.0410 - val_loss: 0.0347 - val_acc: 0.2523 - val_mean_squared_error: 0.0347
Epoch 9/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0376 - acc: 0.2877 - mean_squared_error: 0.0376Epoch 00008: val_loss improved from 0.03472 to 0.03132, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0376 - acc: 0.2874 - mean_squared_error: 0.0376 - val_loss: 0.0313 - val_acc: 0.2523 - val_mean_squared_error: 0.0313
Epoch 10/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0352 - acc: 0.2966 - mean_squared_error: 0.0352Epoch 00009: val_loss improved from 0.03132 to 0.02794, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0353 - acc: 0.2985 - mean_squared_error: 0.0353 - val_loss: 0.0279 - val_acc: 0.2523 - val_mean_squared_error: 0.0279
Epoch 11/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0324 - acc: 0.3072 - mean_squared_error: 0.0324Epoch 00010: val_loss improved from 0.02794 to 0.02638, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0324 - acc: 0.3090 - mean_squared_error: 0.0324 - val_loss: 0.0264 - val_acc: 0.2523 - val_mean_squared_error: 0.0264
Epoch 12/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0308 - acc: 0.3131 - mean_squared_error: 0.0308Epoch 00011: val_loss improved from 0.02638 to 0.02461, saving model to model6-SGD.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0307 - acc: 0.3119 - mean_squared_error: 0.0307 - val_loss: 0.0246 - val_acc: 0.2570 - val_mean_squared_error: 0.0246
--- using optimizer: RMSprop --- saving weights in: model6-RMSprop.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0379 - acc: 0.3744 - mean_squared_error: 0.0379 Epoch 00000: val_loss improved from inf to 0.00958, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0378 - acc: 0.3744 - mean_squared_error: 0.0378 - val_loss: 0.0096 - val_acc: 0.6939 - val_mean_squared_error: 0.0096
Epoch 2/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0122 - acc: 0.5189 - mean_squared_error: 0.0122Epoch 00001: val_loss improved from 0.00958 to 0.00665, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0122 - acc: 0.5210 - mean_squared_error: 0.0122 - val_loss: 0.0067 - val_acc: 0.6963 - val_mean_squared_error: 0.0067
Epoch 3/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0071 - acc: 0.6250 - mean_squared_error: 0.0071Epoch 00002: val_loss improved from 0.00665 to 0.00445, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0071 - acc: 0.6250 - mean_squared_error: 0.0071 - val_loss: 0.0044 - val_acc: 0.6963 - val_mean_squared_error: 0.0044
Epoch 4/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0055 - acc: 0.6604 - mean_squared_error: 0.0055Epoch 00003: val_loss improved from 0.00445 to 0.00374, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0055 - acc: 0.6612 - mean_squared_error: 0.0055 - val_loss: 0.0037 - val_acc: 0.6963 - val_mean_squared_error: 0.0037
Epoch 5/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0048 - acc: 0.6698 - mean_squared_error: 0.0048Epoch 00004: val_loss improved from 0.00374 to 0.00327, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0048 - acc: 0.6700 - mean_squared_error: 0.0048 - val_loss: 0.0033 - val_acc: 0.6963 - val_mean_squared_error: 0.0033
Epoch 6/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0042 - acc: 0.6763 - mean_squared_error: 0.0042Epoch 00005: val_loss improved from 0.00327 to 0.00271, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0042 - acc: 0.6782 - mean_squared_error: 0.0042 - val_loss: 0.0027 - val_acc: 0.7009 - val_mean_squared_error: 0.0027
Epoch 7/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0037 - acc: 0.7011 - mean_squared_error: 0.0037Epoch 00006: val_loss improved from 0.00271 to 0.00270, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0037 - acc: 0.6998 - mean_squared_error: 0.0037 - val_loss: 0.0027 - val_acc: 0.7009 - val_mean_squared_error: 0.0027
Epoch 8/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0035 - acc: 0.6922 - mean_squared_error: 0.0035Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0035 - acc: 0.6928 - mean_squared_error: 0.0035 - val_loss: 0.0029 - val_acc: 0.6986 - val_mean_squared_error: 0.0029
Epoch 9/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0033 - acc: 0.7034 - mean_squared_error: 0.0033Epoch 00008: val_loss improved from 0.00270 to 0.00236, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0033 - acc: 0.7033 - mean_squared_error: 0.0033 - val_loss: 0.0024 - val_acc: 0.6963 - val_mean_squared_error: 0.0024
Epoch 10/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0032 - acc: 0.6958 - mean_squared_error: 0.0032Epoch 00009: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0032 - acc: 0.6963 - mean_squared_error: 0.0032 - val_loss: 0.0024 - val_acc: 0.6893 - val_mean_squared_error: 0.0024
Epoch 11/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0030 - acc: 0.7005 - mean_squared_error: 0.0030Epoch 00010: val_loss improved from 0.00236 to 0.00236, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0030 - acc: 0.7015 - mean_squared_error: 0.0030 - val_loss: 0.0024 - val_acc: 0.7033 - val_mean_squared_error: 0.0024
Epoch 12/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0029 - acc: 0.7134 - mean_squared_error: 0.0029Epoch 00011: val_loss improved from 0.00236 to 0.00212, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0029 - acc: 0.7132 - mean_squared_error: 0.0029 - val_loss: 0.0021 - val_acc: 0.6986 - val_mean_squared_error: 0.0021
--- using optimizer: Adam --- saving weights in: model6-Adam.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0028 - acc: 0.7105 - mean_squared_error: 0.0028 Epoch 00000: val_loss improved from inf to 0.00215, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0028 - acc: 0.7103 - mean_squared_error: 0.0028 - val_loss: 0.0021 - val_acc: 0.6963 - val_mean_squared_error: 0.0021
Epoch 2/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0026 - acc: 0.7158 - mean_squared_error: 0.0026Epoch 00001: val_loss improved from 0.00215 to 0.00207, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0026 - acc: 0.7150 - mean_squared_error: 0.0026 - val_loss: 0.0021 - val_acc: 0.6963 - val_mean_squared_error: 0.0021
Epoch 3/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0025 - acc: 0.7070 - mean_squared_error: 0.0025Epoch 00002: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0025 - acc: 0.7062 - mean_squared_error: 0.0025 - val_loss: 0.0021 - val_acc: 0.6986 - val_mean_squared_error: 0.0021
Epoch 4/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0025 - acc: 0.7193 - mean_squared_error: 0.0025Epoch 00003: val_loss improved from 0.00207 to 0.00190, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0025 - acc: 0.7202 - mean_squared_error: 0.0025 - val_loss: 0.0019 - val_acc: 0.7009 - val_mean_squared_error: 0.0019
Epoch 5/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0024 - acc: 0.7158 - mean_squared_error: 0.0024Epoch 00004: val_loss improved from 0.00190 to 0.00186, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0024 - acc: 0.7161 - mean_squared_error: 0.0024 - val_loss: 0.0019 - val_acc: 0.7009 - val_mean_squared_error: 0.0019
Epoch 6/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7193 - mean_squared_error: 0.0023Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0023 - acc: 0.7190 - mean_squared_error: 0.0023 - val_loss: 0.0019 - val_acc: 0.6986 - val_mean_squared_error: 0.0019
Epoch 7/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0023 - acc: 0.7241 - mean_squared_error: 0.0023Epoch 00006: val_loss improved from 0.00186 to 0.00184, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0023 - acc: 0.7231 - mean_squared_error: 0.0023 - val_loss: 0.0018 - val_acc: 0.7033 - val_mean_squared_error: 0.0018
Epoch 8/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0022 - acc: 0.7347 - mean_squared_error: 0.0022Epoch 00007: val_loss improved from 0.00184 to 0.00180, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0022 - acc: 0.7348 - mean_squared_error: 0.0022 - val_loss: 0.0018 - val_acc: 0.7173 - val_mean_squared_error: 0.0018
Epoch 9/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0022 - acc: 0.7229 - mean_squared_error: 0.0022Epoch 00008: val_loss improved from 0.00180 to 0.00179, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0022 - acc: 0.7220 - mean_squared_error: 0.0022 - val_loss: 0.0018 - val_acc: 0.6963 - val_mean_squared_error: 0.0018
Epoch 10/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7264 - mean_squared_error: 0.0021Epoch 00009: val_loss improved from 0.00179 to 0.00166, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0021 - acc: 0.7255 - mean_squared_error: 0.0021 - val_loss: 0.0017 - val_acc: 0.7009 - val_mean_squared_error: 0.0017
Epoch 11/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7199 - mean_squared_error: 0.0021Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0021 - acc: 0.7208 - mean_squared_error: 0.0021 - val_loss: 0.0018 - val_acc: 0.7079 - val_mean_squared_error: 0.0018
Epoch 12/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7217 - mean_squared_error: 0.0020Epoch 00011: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0020 - acc: 0.7225 - mean_squared_error: 0.0020 - val_loss: 0.0017 - val_acc: 0.7173 - val_mean_squared_error: 0.0017
--- using optimizer: Nadam --- saving weights in: model6-Nadam.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7311 - mean_squared_error: 0.0021 Epoch 00000: val_loss improved from inf to 0.00168, saving model to model6-Nadam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0021 - acc: 0.7331 - mean_squared_error: 0.0021 - val_loss: 0.0017 - val_acc: 0.7056 - val_mean_squared_error: 0.0017
Epoch 2/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0021 - acc: 0.7270 - mean_squared_error: 0.0021Epoch 00001: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0021 - acc: 0.7261 - mean_squared_error: 0.0021 - val_loss: 0.0018 - val_acc: 0.7290 - val_mean_squared_error: 0.0018
Epoch 3/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7188 - mean_squared_error: 0.0020Epoch 00002: val_loss improved from 0.00168 to 0.00164, saving model to model6-Nadam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0020 - acc: 0.7190 - mean_squared_error: 0.0020 - val_loss: 0.0016 - val_acc: 0.7079 - val_mean_squared_error: 0.0016
Epoch 4/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0020 - acc: 0.7329 - mean_squared_error: 0.0020Epoch 00003: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0020 - acc: 0.7325 - mean_squared_error: 0.0020 - val_loss: 0.0017 - val_acc: 0.7056 - val_mean_squared_error: 0.0017
Epoch 5/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7199 - mean_squared_error: 0.0019Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0019 - acc: 0.7202 - mean_squared_error: 0.0019 - val_loss: 0.0017 - val_acc: 0.7150 - val_mean_squared_error: 0.0017
Epoch 6/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7323 - mean_squared_error: 0.0019 - ETA: 0s - loss: 0.0019 - acc: 0.7298 - mean_squared_error: 0.0019Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0019 - acc: 0.7313 - mean_squared_error: 0.0019 - val_loss: 0.0017 - val_acc: 0.7079 - val_mean_squared_error: 0.0017
Epoch 7/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7311 - mean_squared_error: 0.0019Epoch 00006: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0019 - acc: 0.7307 - mean_squared_error: 0.0019 - val_loss: 0.0017 - val_acc: 0.6986 - val_mean_squared_error: 0.0017
Epoch 8/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0019 - acc: 0.7223 - mean_squared_error: 0.0019 - ETA: 1s - loss: 0.0019 - acc: 0.7289 - mean_squared_error: 0.0019Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0019 - acc: 0.7231 - mean_squared_error: 0.0019 - val_loss: 0.0017 - val_acc: 0.7033 - val_mean_squared_error: 0.0017
Epoch 9/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7370 - mean_squared_error: 0.0018Epoch 00008: val_loss improved from 0.00164 to 0.00162, saving model to model6-Nadam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0018 - acc: 0.7360 - mean_squared_error: 0.0018 - val_loss: 0.0016 - val_acc: 0.7173 - val_mean_squared_error: 0.0016
Epoch 10/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7347 - mean_squared_error: 0.0018Epoch 00009: val_loss did not improve
1712/1712 [==============================] - 4s - loss: 0.0018 - acc: 0.7331 - mean_squared_error: 0.0018 - val_loss: 0.0017 - val_acc: 0.7126 - val_mean_squared_error: 0.0017
Epoch 11/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0017 - acc: 0.7358 - mean_squared_error: 0.0017 - ETA: 0s - loss: 0.0017 - acc: 0.7418 - mean_squared_error: 0.0017Epoch 00010: val_loss improved from 0.00162 to 0.00158, saving model to model6-Nadam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0018 - acc: 0.7360 - mean_squared_error: 0.0018 - val_loss: 0.0016 - val_acc: 0.7079 - val_mean_squared_error: 0.0016
Epoch 12/12
1696/1712 [============================>.] - ETA: 0s - loss: 0.0018 - acc: 0.7276 - mean_squared_error: 0.0018Epoch 00011: val_loss improved from 0.00158 to 0.00155, saving model to model6-Nadam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0018 - acc: 0.7266 - mean_squared_error: 0.0018 - val_loss: 0.0016 - val_acc: 0.7103 - val_mean_squared_error: 0.0016
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-67-46ba6c686a45> in <module>()
     16     model6.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy', 'mse'] )
     17 
---> 18     filepath = 'model6-' + opt + '.weights.best.hdf5'
     19     print('--- using optimizer: {} --- saving weights in: {} ---\n'.format(opt, filepath))
     20 

TypeError: Can't convert 'SGD' object to str implicitly

Looks like the RMSProp and Adam optimizers show more promise than others, in terms of accuracy and loss.

Let's retrain a little bit more and see.

In [68]:
from keras.callbacks import ReduceLROnPlateau

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=3, min_lr=0.0003)

N_EPOCHS = 20

optimizers = ['RMSprop', 'Adam']
for opt in optimizers:

    ## compile model
    model6.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy', 'mse'] )
    
    filepath = 'model6-' + opt + '.weights.best.hdf5'
    print('--- using optimizer: {} --- saving weights in: {} ---\n'.format(opt, filepath))
    
    checkpointer = ModelCheckpoint(filepath=filepath, verbose=1, 
                               save_best_only=True)

    ## TODO: Train the model
    hist = model6.fit(X_train, y_train,
                batch_size=32, 
                epochs=N_EPOCHS,
                validation_split=0.2,
                verbose=1,
                callbacks=[checkpointer, reduce_lr],
                shuffle=True)
    ## plot graph
    print(' --- history for: {} ---'.format(opt))
    show_history_graph(hist)
--- using optimizer: RMSprop --- saving weights in: model6-RMSprop.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0017 - acc: 0.7305 - mean_squared_error: 0.0017  - ETA: 6s - loss: 0.0019 - acc: 0.7227 - mean_squared_error: 0.0019Epoch 00000: val_loss improved from inf to 0.00151, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0017 - acc: 0.7301 - mean_squared_error: 0.0017 - val_loss: 0.0015 - val_acc: 0.7126 - val_mean_squared_error: 0.0015
Epoch 2/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0017 - acc: 0.7465 - mean_squared_error: 0.0017Epoch 00001: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0017 - acc: 0.7477 - mean_squared_error: 0.0017 - val_loss: 0.0015 - val_acc: 0.7103 - val_mean_squared_error: 0.0015
Epoch 3/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7506 - mean_squared_error: 0.0016Epoch 00002: val_loss improved from 0.00151 to 0.00146, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7500 - mean_squared_error: 0.0016 - val_loss: 0.0015 - val_acc: 0.7126 - val_mean_squared_error: 0.0015
Epoch 4/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7335 - mean_squared_error: 0.0016Epoch 00003: val_loss improved from 0.00146 to 0.00141, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7307 - mean_squared_error: 0.0016 - val_loss: 0.0014 - val_acc: 0.7290 - val_mean_squared_error: 0.0014
Epoch 5/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7412 - mean_squared_error: 0.0016Epoch 00004: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7407 - mean_squared_error: 0.0016 - val_loss: 0.0014 - val_acc: 0.7196 - val_mean_squared_error: 0.0014
Epoch 6/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7323 - mean_squared_error: 0.0016Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7319 - mean_squared_error: 0.0016 - val_loss: 0.0014 - val_acc: 0.7150 - val_mean_squared_error: 0.0014
Epoch 7/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7447 - mean_squared_error: 0.0016Epoch 00006: val_loss improved from 0.00141 to 0.00134, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7465 - mean_squared_error: 0.0016 - val_loss: 0.0013 - val_acc: 0.7196 - val_mean_squared_error: 0.0013
Epoch 8/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0016 - acc: 0.7364 - mean_squared_error: 0.0016Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0016 - acc: 0.7371 - mean_squared_error: 0.0016 - val_loss: 0.0014 - val_acc: 0.7220 - val_mean_squared_error: 0.0014
Epoch 9/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7471 - mean_squared_error: 0.0015Epoch 00008: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7477 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7056 - val_mean_squared_error: 0.0014
Epoch 10/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7465 - mean_squared_error: 0.0015Epoch 00009: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7459 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7196 - val_mean_squared_error: 0.0013
Epoch 11/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7482 - mean_squared_error: 0.0015Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7482 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7126 - val_mean_squared_error: 0.0014
Epoch 12/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7447 - mean_squared_error: 0.0015Epoch 00011: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7436 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7243 - val_mean_squared_error: 0.0014
Epoch 13/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7459 - mean_squared_error: 0.0015Epoch 00012: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7459 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7173 - val_mean_squared_error: 0.0014
Epoch 14/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7394 - mean_squared_error: 0.0015Epoch 00013: val_loss improved from 0.00134 to 0.00133, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7389 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7243 - val_mean_squared_error: 0.0013
Epoch 15/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7412 - mean_squared_error: 0.0015Epoch 00014: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7418 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7126 - val_mean_squared_error: 0.0014
Epoch 16/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7494 - mean_squared_error: 0.0015Epoch 00015: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7500 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7126 - val_mean_squared_error: 0.0013
Epoch 17/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7417 - mean_squared_error: 0.0015Epoch 00016: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7424 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7243 - val_mean_squared_error: 0.0013
Epoch 18/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7388 - mean_squared_error: 0.0015Epoch 00017: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7395 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7126 - val_mean_squared_error: 0.0014
Epoch 19/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7441 - mean_squared_error: 0.0015Epoch 00018: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7412 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7243 - val_mean_squared_error: 0.0014
Epoch 20/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7417 - mean_squared_error: 0.0015Epoch 00019: val_loss improved from 0.00133 to 0.00132, saving model to model6-RMSprop.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7407 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7196 - val_mean_squared_error: 0.0013
 --- history for: RMSprop ---
--- using optimizer: Adam --- saving weights in: model6-Adam.weights.best.hdf5 ---

Train on 1712 samples, validate on 428 samples
Epoch 1/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7577 - mean_squared_error: 0.0015 Epoch 00000: val_loss improved from inf to 0.00138, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7576 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7220 - val_mean_squared_error: 0.0014
Epoch 2/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7476 - mean_squared_error: 0.0015Epoch 00001: val_loss improved from 0.00138 to 0.00134, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7488 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7266 - val_mean_squared_error: 0.0013
Epoch 3/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7412 - mean_squared_error: 0.0015Epoch 00002: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7424 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7336 - val_mean_squared_error: 0.0014
Epoch 4/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7412 - mean_squared_error: 0.0015Epoch 00003: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7418 - mean_squared_error: 0.0015 - val_loss: 0.0014 - val_acc: 0.7243 - val_mean_squared_error: 0.0014
Epoch 5/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0015 - acc: 0.7529 - mean_squared_error: 0.0015Epoch 00004: val_loss improved from 0.00134 to 0.00133, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0015 - acc: 0.7535 - mean_squared_error: 0.0015 - val_loss: 0.0013 - val_acc: 0.7313 - val_mean_squared_error: 0.0013
Epoch 6/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7500 - mean_squared_error: 0.0014Epoch 00005: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7494 - mean_squared_error: 0.0014 - val_loss: 0.0014 - val_acc: 0.7173 - val_mean_squared_error: 0.0014
Epoch 7/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7577 - mean_squared_error: 0.0014Epoch 00006: val_loss improved from 0.00133 to 0.00132, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7564 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7196 - val_mean_squared_error: 0.0013
Epoch 8/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7642 - mean_squared_error: 0.0014        Epoch 00007: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7629 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7266 - val_mean_squared_error: 0.0013
Epoch 9/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7577 - mean_squared_error: 0.0014Epoch 00008: val_loss improved from 0.00132 to 0.00131, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7576 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7336 - val_mean_squared_error: 0.0013
Epoch 10/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7571 - mean_squared_error: 0.0014Epoch 00009: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7576 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7290 - val_mean_squared_error: 0.0013
Epoch 11/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7541 - mean_squared_error: 0.0014Epoch 00010: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7553 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7313 - val_mean_squared_error: 0.0013
Epoch 12/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7571 - mean_squared_error: 0.0014Epoch 00011: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7564 - mean_squared_error: 0.0014 - val_loss: 0.0014 - val_acc: 0.7336 - val_mean_squared_error: 0.0014
Epoch 13/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7612 - mean_squared_error: 0.0014Epoch 00012: val_loss improved from 0.00131 to 0.00130, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7599 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7220 - val_mean_squared_error: 0.0013
Epoch 14/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7518 - mean_squared_error: 0.0014Epoch 00013: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7523 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7407 - val_mean_squared_error: 0.0013
Epoch 15/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7494 - mean_squared_error: 0.0014Epoch 00014: val_loss improved from 0.00130 to 0.00129, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7500 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7383 - val_mean_squared_error: 0.0013
Epoch 16/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7476 - mean_squared_error: 0.0014Epoch 00015: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7488 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7383 - val_mean_squared_error: 0.0013
Epoch 17/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7571 - mean_squared_error: 0.0014Epoch 00016: val_loss did not improve
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7582 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7336 - val_mean_squared_error: 0.0013
Epoch 18/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7565 - mean_squared_error: 0.0014Epoch 00017: val_loss improved from 0.00129 to 0.00128, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 5s - loss: 0.0014 - acc: 0.7564 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7360 - val_mean_squared_error: 0.0013
Epoch 19/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7683 - mean_squared_error: 0.0014Epoch 00018: val_loss improved from 0.00128 to 0.00125, saving model to model6-Adam.weights.best.hdf5
1712/1712 [==============================] - 4s - loss: 0.0014 - acc: 0.7687 - mean_squared_error: 0.0014 - val_loss: 0.0012 - val_acc: 0.7477 - val_mean_squared_error: 0.0012
Epoch 20/20
1696/1712 [============================>.] - ETA: 0s - loss: 0.0014 - acc: 0.7382 - mean_squared_error: 0.0014Epoch 00019: val_loss did not improve
1712/1712 [==============================] - 4s - loss: 0.0014 - acc: 0.7389 - mean_squared_error: 0.0014 - val_loss: 0.0013 - val_acc: 0.7383 - val_mean_squared_error: 0.0013
 --- history for: Adam ---

Results from Optimizer Tests

So looks like we are able to achieve accuracy of 74%, with a validation loss of 0.00125 with Model6 using Adam optimizer. This is a good enough result.

Visualize a Subset of the Test Predictions

Note This uses previously saved model weights, so that we don't have to train the model all over again. Saves us a ton of time, especially when trained on a laptop!.

Our saved model weights are in model6-Adam.weights.best.hdf5

In [22]:
from keras.models import load_model

### Load a saved best model
model6 = load_model('model6-Adam.weights.best.hdf5')
In [23]:
model6.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 94, 94, 8)         80        
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 47, 47, 8)         0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 47, 47, 8)         0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 46, 46, 16)        528       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 23, 23, 16)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 23, 23, 16)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 22, 22, 32)        2080      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 11, 11, 32)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 11, 11, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 3872)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 256)               991488    
_________________________________________________________________
dropout_4 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 128)               32896     
_________________________________________________________________
dropout_5 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3870      
=================================================================
Total params: 1,030,942.0
Trainable params: 1,030,942.0
Non-trainable params: 0.0
_________________________________________________________________
In [24]:
### Lets visualize results

### Visualize some results

# MODEL switcher
model = model6     # CHANGE IF NECESSARY

y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)
In [ ]:
 
In [ ]:
 

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer:

I created several models - with basic CNN architecture as follows: Convolution layers with MaxPools, with increasing depth of filters (to gather more feature maps), connected to 1-2 Dense layers, and finally to a Dense layer of 30 nodes for the output.

  • A Conv layer with kernel (3,3) and N filters N=(8, 16, 32)
  • MaxPool2D layer with kernel 2 - to reduce dimensions
  • Dropout (0.1 - 0.2) - for regularization
  • Conv layer with kernel (3,3) and N filters N=(16, 32, 64)
  • MaxPool2D layer with kernel 2 - to reduce dimensions
  • Dropout (0.1 - 0.2) - for regularization
  • Conv layer with kernel (3,3) and N filters N=(32, 64, 128)
  • MaxPool2D layer with kernel 2 - to reduce dimensions
  • Dropout (0.1 - 0.2) - for regularization
  • TWO Dense layers of N = (512, 256) or (256, 128)
  • Dropout (0.5) - for regularization
  • Final Dense layer (30) for the 15 keypoints

I experimented with various combinations of the above architecture, noting down the increases in accuracy and decreases in loss, using mainly the Adam optimizer, and later experimenting with a few others as well.

I finally settled on model6 which was relatively smaller model (~1M params) compared to bigger ones (from ~2M to 8M params) that yielded accuracy ~74%, and loss 0.0013.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: I tested out a few optimizers: Adam, RMSProp, SGD, Nesterov. Of these, initially, I tested with Adam, as this is usually shown to perfom the best with CNNs. (See http://danielnouri.org/notes/2014/12/17/using-convolutional-neural-nets-to-detect-facial-keypoints-tutorial/ and Stanford CS231N course)

Because this is a regression task over 30 continuous (x,y) pairs, rather than a classfiction (categorical_crossentropy), the loss function is a mean squared error loss. SGD did not give good results, while the best results were achieved with either Adam or RMSProp optimizer. So I chose Adam for final results.

I ran the final model for 12 + 20 epochs, which yielded decently good results noted above.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [25]:
## TODO: Visualize the training and validation loss of your neural network


### ANSWER -- Losses have been visualized above with the respective models

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer:

Yes, there was overfitting in several cases. I experimented with using Dropout layers after MaxPools and after Dense layers to reduce overfitting. This helped with the results, and yielded the loss curves shown above.

Further overfitting could be reduced by using data augmentation (which was not performed here).

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [25]:
y_test = model.predict(X_test)  ### NOTE: this uses Model6 above
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [26]:
# Load in color image for face detection
obama = cv2.imread('images/obamas4.jpg')


# Convert the image to RGB colorspace
obama_copy = cv2.cvtColor(obama, cv2.COLOR_BGR2RGB)


# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(obama_copy)
Out[26]:
<matplotlib.image.AxesImage at 0x14211b240>
In [27]:
### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
## TODO : Paint the predicted keypoints on the test image

def face_keypoint_detection(image, model):
    ''' Detect keypoints in the faces in given image, using given model
        Return image with face keypoints drawn on it
    '''
    image_with_detections = np.copy(image)
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.08, 20)

    ## Get bounding box for each detected face
    for (x,y,w,h) in faces:
        # add red bbox
        cv2.rectangle(image_with_detections,
                 (x,y),
                 (x+w, y+h),
                 (255,0,0), 3)
    
        # delta
        delta = max(w, h)
        if (w >= h):
            y -= int((w-h) / 2)
        else:
            x -= int((h-w) / 2)
        
        # get a face patch, and resize it to 96x96
        face = cv2.resize(gray[y: y+delta, x:x+delta],
                     (96, 96), interpolation=cv2.INTER_CUBIC) / 255.
    
        xface = np.array([face])
        xface = xface[..., np.newaxis]
    
        # now detect keypoints (Ys) - and rescale
        face_keypoints = model.predict(xface)[0] * (delta/2) + (delta/2)  # rescale the ys
        keypoints_x = face_keypoints[0::2] + x
        keypoints_y = face_keypoints[1::2] + y
        # draw dots on keypoints
        for (x,y) in zip(keypoints_x, keypoints_y):
            cv2.circle(image_with_detections, (x,y), 3, (0,255,0), -1)
            
    # return this image
    return image_with_detections
In [28]:
## run the function on Obama image
obama_with_detections = face_keypoint_detection(obama_copy, model6)   # use the model6 

# Display the image with the detections
fig = plt.figure(figsize = (10,10))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with keypoint detections')
ax1.imshow(obama_with_detections)
    
Out[28]:
<matplotlib.image.AxesImage at 0x11a5400b8>
In [30]:
### Save the model weights
model6.save('my_model.h5')

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [29]:
import cv2
import time 
from keras.models import load_model
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        # plot image from camera with detections marked
        
        frame_keypoint = face_keypoint_detection(frame, model6)
        
        cv2.imshow("face detection activated", frame_keypoint)
        
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [30]:
# Run your keypoint face painter
# laptop_camera_go()

Here's the image captured.

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [31]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [32]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [33]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
the alpha channel here looks like
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109]), array([ 687,  688,  689, ..., 2376, 2377, 2378]))

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [34]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[34]:
<matplotlib.image.AxesImage at 0x1421648d0>
In [43]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
## TODO : Paint the predicted keypoints on the test image

def overlay_sunglasses(image, model, sunglasses):
    ''' Detect keypoints in the faces in given image, using given model
        Return image with face keypoints drawn on it
    '''
    image_with_detections = np.copy(image)
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.08, 20)

    ## Get bounding box for each detected face
    for (x,y,w,h) in faces:
        # add red bbox -- ignore
        # cv2.rectangle(image_with_detections,
        #         (x,y),
        #         (x+w, y+h),
        #         (255,0,0), 3)
    
        # delta
        delta = max(w, h)
        if (w >= h):
            y -= int((w-h) / 2)
        else:
            x -= int((h-w) / 2)
        
        # get a face patch, and resize it to 96x96
        face = cv2.resize(gray[y: y+delta, x:x+delta],
                     (96, 96), interpolation=cv2.INTER_CUBIC) / 255.
    
        xface = np.array([face])
        xface = xface[..., np.newaxis]
    
        # now detect keypoints (Ys) - and rescale
        face_keypoints = model.predict(xface)[0] * (delta/2) + (delta/2)  # rescale the ys
        keypoints_x = face_keypoints[0::2] + x
        keypoints_y = face_keypoints[1::2] + y
        
        # draw dots on keypoints
        #for (x,y) in zip(keypoints_x, keypoints_y):
        #    cv2.circle(image_with_detections, (x,y), 3, (0,255,0), -1)
        
        ### overlay ###
        
        sunglass_h = int((keypoints_y[10] - keypoints_y[9])/1.1)
        sunglass_w = int((keypoints_x[7] - keypoints_x[9])*1.2)
        
        overlay_topL_y = int(keypoints_y[9])
        overlay_topL_x = int(keypoints_x[9])
        
        resized_sunglass = cv2.resize(sunglasses, (sunglass_w, sunglass_h))
        
        # transparent region
        alpha_region = resized_sunglass[:,:,3] != 0
        
        # add overlay
        image_with_detections[overlay_topL_y: overlay_topL_y + sunglass_h, 
                             overlay_topL_x: overlay_topL_x + sunglass_w, :][alpha_region] = \
        resized_sunglass[:,:,:3][alpha_region]
            
    # return this image
    return image_with_detections
In [44]:
# copy of obama original
obama_copy = np.copy(image)

## run the function on Obama image
obama_glasses = overlay_sunglasses(obama_copy, model6, sunglasses)   # use the model6 

# Display the image with the detections
fig = plt.figure(figsize = (10,10))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Obamas with sunglasses')
ax1.imshow(obama_glasses)
Out[44]:
<matplotlib.image.AxesImage at 0x1289370b8>
In [ ]:
 
In [ ]:
 

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [45]:
import cv2
import time 
from keras.models import load_model
import numpy as np

def laptop_camera_go_sunglass():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        
        sunglass_frame = overlay_sunglasses(frame, model6, sunglasses)
        
        cv2.imshow("face detection activated", sunglass_frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [ ]:
# Load facial landmark detector model
#model = load_model('my_model.h5')

# Run sunglasses painter
laptop_camera_go_sunglass()

Here's the captured image

In [ ]: